#include "communicationwindow.h"
#include "ui_communicationwindow.h"

CommunicationWindow::CommunicationWindow(QTcpSocket * clientSocket,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::CommunicationWindow)
    , clientSocket(clientSocket)
{
    ui->setupUi(this);
    QPixmap pixmap("../../../resource/4.jpg");
    // 创建一个QPalette实例
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);
    // 设置窗口的调色板
    this->setPalette(palette);
    // 设置窗口标题
    this->setWindowTitle("医患交流平台");

    // 添加图片发送按钮
    imageButton = new QPushButton("发送图片", this);
    imageButton->setGeometry(450, 350, 80, 30); // 根据界面调整位置
    imageButton->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; border: none; border-radius: 4px; }");
    connect(imageButton, &QPushButton::clicked, this, &CommunicationWindow::on_ImageButton_clicked);

    // get doctor's id and name
    QString patientQueryStr = "SELECT DISTINCT P.patient_id , P.name FROM Chats C  JOIN Patients P ON C.patient_id = P.patient_id  WHERE C.doctor_id = "+QString::number(currentUserID)+";";
    qDebug()<<patientQueryStr;
    clientSocket->write(patientQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QStringList items = receivedData.split('\n');
            for (const QString &item : items) {
                if(item.length()<3)
                    continue;
                ui->DoctorBox->addItem(item);
            }
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }

    timer = new QTimer(this);
    timer->start(1000);
    connect(timer, &QTimer::timeout, this, &CommunicationWindow::DialogEdit_update);
}


void CommunicationWindow::on_DoctorBox_currentIndexChanged(){
    ui->DialogEdit->clear();
    qDebug()<< "Selected option: " << ui->DoctorBox->currentText();
    // get select Doctor ID
    QString selectDoctorStr = ui->DoctorBox->currentText();
    QString patientIDStr = selectDoctorStr.section('|', 0, 0);
    QString doctorIDStr = QString::number(currentUserID);
    // get dialog
    QString dialogQueryStr = "SELECT * FROM Chats WHERE patient_id = "+patientIDStr+
                             " AND doctor_id = "+doctorIDStr+" ORDER BY date ASC;";
    clientSocket->write(dialogQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QStringList items = receivedData.split('\n');
            for (const QString &item : items) {
                qDebug()<<item;
                QStringList atomItems = item.split('|');
                if(atomItems.size()<6)
                    break;

                // 检查消息类型
                QString messageType = atomItems.size() > 6 ? atomItems[6] : "text";

                if(atomItems[3]=="outgoing")
                {
                    ui->DialogEdit->append(QString("<span style='color: red;'>")+selectDoctorStr.section('|', 1, 1)+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: red;'>")+atomItems[4]+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: black;'>")+atomItems[5]+QString("</span>"));
                }
                else{
                    ui->DialogEdit->append(QString("<span style='color: blue;'>")+currentUserTrueName+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: blue;'>")+atomItems[4]+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: black;'>")+atomItems[5]+QString("</span>"));
                }

            }
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }
}

void CommunicationWindow::on_ImageButton_clicked() {
    // 检查是否选择了患者
    if (ui->DoctorBox->currentText().isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择一个患者");
        return;
    }

    // 选择图片文件
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "选择图片",
        "",
        "Images (*.png *.jpg *.jpeg *.bmp *.gif)"
        );

    if (fileName.isEmpty()) {
        return;
    }

    // 读取图片文件
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "错误", "无法读取图片文件");
        return;
    }

    QByteArray imageData = file.readAll();
    file.close();

    // 检查文件大小（限制为5MB）
    if (imageData.size() > 5 * 1024 * 1024) {
        QMessageBox::warning(this, "错误", "图片文件过大，请选择小于5MB的图片");
        return;
    }

    // 获取患者ID
    QString selectPatientStr = ui->DoctorBox->currentText();
    int patientId = selectPatientStr.section('|', 0, 0).toInt();

    // 构造JSON消息
    QJsonObject json;
    json["patient_id"] = patientId;
    json["doctor_id"] = currentUserID;
    json["direction"] = "incoming";  // 医生发给患者
    json["filename"] = QFileInfo(fileName).fileName();
    json["image_data"] = QString::fromUtf8(imageData.toBase64());

    // 发送JSON消息
    QJsonDocument doc(json);
    QString jsonString = doc.toJson(QJsonDocument::Compact) + "\n";

    clientSocket->write(jsonString.toUtf8());
    clientSocket->flush();

    // 等待服务器响应
    if (clientSocket->waitForReadyRead(3000)) {
        QByteArray response = clientSocket->readAll();
        QString responseStr = QString::fromUtf8(response);

        if (responseStr.startsWith("success:")) {
            // 在聊天框中显示图片消息
            ui->DialogEdit->append("<span style='color: blue;'>您</span>");
            ui->DialogEdit->append("<span style='color: green;'>[图片: " + QFileInfo(fileName).fileName() + "]</span>");

            // 滚动到底部
            QScrollBar *scrollBar = ui->DialogEdit->verticalScrollBar();
            scrollBar->setValue(scrollBar->maximum());

            QMessageBox::information(this, "成功", "图片发送成功");
        } else {
            QMessageBox::warning(this, "错误", "图片发送失败: " + responseStr);
        }
    } else {
        QMessageBox::warning(this, "错误", "发送超时，请重试");
    }
}

void CommunicationWindow::on_BackButton_clicked(){
    emit back();
}

void CommunicationWindow::on_SendButton_clicked(){
    // 获取当前日期时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 格式化日期时间为"yyyy-MM-dd hh:mm:ss"格式
    QString formattedDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    QString selectDoctorStr = ui->DoctorBox->currentText();
    QString patientIDStr = selectDoctorStr.section('|', 0, 0);
    QString doctorIDStr = QString::number(currentUserID);
    QString sendStr = "INSERT INTO Chats (patient_id, doctor_id, direction, date, content) \
        VALUES ("+patientIDStr+", "+doctorIDStr+", 'incoming', '"+formattedDateTime+"', '"+ui->SendEdit->toPlainText()+"');";
    qDebug()<<sendStr;
    clientSocket->write(sendStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ui->DialogEdit->append(QString("<span style='color: blue;'>")+currentUserTrueName+QString("</span>"));
            ui->DialogEdit->append(QString("<span style='color: blue;'>")+formattedDateTime+QString("</span>"));
            ui->DialogEdit->append(QString("<span style='color: black;'>")+ui->SendEdit->toPlainText()+QString("</span>"));
        } else {
            QMessageBox::warning(this,tr("Error"),receivedData);
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }
    ui->SendEdit->clear();
}

void CommunicationWindow::DialogEdit_update(){
    // remember currentScrollPosition
    int currentScrollPosition =0;
    QScrollBar *scrollbar = ui->DialogEdit->verticalScrollBar();
    if(scrollbar){
        currentScrollPosition = scrollbar->value();
    }
    ui->DialogEdit->clear();
    // get select Doctor ID
    QString selectDoctorStr = ui->DoctorBox->currentText();
    QString patientIDStr = selectDoctorStr.section('|', 0, 0);
    QString doctorIDStr = QString::number(currentUserID);
    // get dialog
    QString dialogQueryStr = "SELECT * FROM Chats WHERE patient_id = "+patientIDStr+ \
                             " AND doctor_id = "+doctorIDStr+" ORDER BY date ASC;";
    clientSocket->write(dialogQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000); // 等待数据写入完成，超时时间为1秒

    if (clientSocket->waitForReadyRead(3000)) { // 等待数据接收，超时时间为3秒
        // 接收数据
        QByteArray data = clientSocket->readAll();

        // 将数据转换为字符串
        QString receivedData = QString::fromUtf8(data);

        // 检查接收到的数据是否为"failed"
        if (receivedData == "failed") {
            ;
        } else {
            QStringList items = receivedData.split('\n');
            for (const QString &item : items) {
                QStringList atomItems = item.split('|');
                if(atomItems.size()<6)
                    break;
                if(atomItems[3]=="outgoing")
                {
                    ui->DialogEdit->append(QString("<span style='color: red;'>")+selectDoctorStr.section('|', 1, 1)+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: red;'>")+atomItems[4]+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: black;'>")+atomItems[5]+QString("</span>"));
                }
                else{
                    ui->DialogEdit->append(QString("<span style='color: blue;'>")+currentUserTrueName+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: blue;'>")+atomItems[4]+QString("</span>"));
                    ui->DialogEdit->append(QString("<span style='color: black;'>")+atomItems[5]+QString("</span>"));
                }

            }
        }
    } else {
        // 如果超时未接收到数据
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }
    if(scrollbar){
        ui->DialogEdit->verticalScrollBar()->setValue(currentScrollPosition);
    }
}

CommunicationWindow::~CommunicationWindow()
{
    timer->stop();
    delete ui;
    delete timer;
}
